package com.tao.plan.common.utils;

import java.security.SecureRandom;

public class CaptchaGenerator {

	// 定义验证码字符集，包括大小写字母和数字
	private static final String CHARACTERS = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
	private static final SecureRandom RANDOM = new SecureRandom();

	/**
	 * 生成指定长度的随机验证码
	 *
	 * @param length 验证码长度
	 * @return 随机生成的验证码
	 */
	public static String generateCaptcha(int length) {
		if (length <= 0) {
			throw new IllegalArgumentException("验证码长度必须大于0");
		}

		StringBuilder captcha = new StringBuilder(length);
		for (int i = 0; i < length; i++) {
			int index = RANDOM.nextInt(CHARACTERS.length());
			captcha.append(CHARACTERS.charAt(index));
		}

		return captcha.toString();
	}

	public static void main(String[] args) {
		// 生成一个6位的验证码
		String captcha = generateCaptcha(6);
		System.out.println("生成的验证码是: " + captcha);
	}
}